// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Form,Radio, Button,Popconfirm, Modal, Row, Col, Input, Select, Cascader, Icon, Checkbox, Tabs, DatePicker, message } from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'
// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
// 当前组件样式
import styles from './projectListDetailStyle.less'
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import { Grid } from 'widget/Grid/index'
import moment from 'moment';

const FormItem = Form.Item
const { RangePicker } = DatePicker
const { Option } = Select;
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const projectListDetailView = function ({ dispatch, model, form }) {
  // 表单的子函数
  const { resetFields, getFieldDecorator, validateFields, setFieldsValue,validateFieldsAndScroll  } = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model
  let { systemData, systemNameList,products,areaList,tableData,keys,tableObj,query, actionType, btnLoading,loading } = modelObj

  const formItemLayoutPro = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
  };

  const columns = [
    {
      title: '序号', dataIndex: 'ruleNo', key: 'ruleNo', width: 80,
      render: function (value, item, index) {
        return index+1
      }
    }, 
    {
      title: '选项内容', dataIndex: 'itemContent', key: 'itemContent', width: 800,
      render: function (value, item, index) {
        return <div>
        <Input value = {item.itemContent}  disabled={actionType == 'check'||query.systemType == '系统项'}
            onChange={(e) => { tableChange(e.target.value, 'itemContent',item.key) }}
          />
      </div>
      }
    },
    {
      title: '是否默认',
      dataIndex: 'Action',
      key: 'Action',
      width: 120,
      render: function (value, item, index) {
        return  <div>
                  <Radio disabled={actionType == 'check'} checked={item.defaultValue} onChange={e=>{defaultValueChange(e.target.checked,item)}}>{'是'}</Radio>
                </div>  
      }
    }
  ]
  const columns1 = [
    {
      title: '序号', dataIndex: 'ruleNo', key: 'ruleNo', width: 80,
      render: function (value, item, index) {
        return index+1
      }
    }, 
    {
      title: '一级', dataIndex: 'itemContent', key: 'itemContent', width: 200,
      render: function (value, item, index) {
        return <div>
        <Input value = {item.itemContent}  disabled={actionType == 'check'||query.systemType == '系统项'}
            onChange={(e) => { tableChange(e.target.value, 'itemContent',item.key) }}
          />
      </div>
      }
    },
    {
      title: '选项内容', dataIndex: 'itemContent1', key: 'itemContent1', width: 600,
      render: function (value, item, index) {
        return <div>
        <Input value = {item.itemContent1}  disabled={actionType == 'check'||query.systemType == '系统项'}
            onChange={(e) => { tableChange(e.target.value, 'itemContent1',item.key) }}
          />
      </div>
      }
    },
    {
      title: '是否默认',
      dataIndex: 'Action',
      key: 'Action',
      width: 120,
      render: function (value, item, index) {
        return  <div>
                  <Radio disabled={actionType == 'check'} checked={item.defaultValue} onChange={e=>{defaultValueChange(e.target.checked,item)}}>{'是'}</Radio>
                </div>  
      }
    }
  ]
 
  // 表格配置------------开始
  const gridProps = {
    nameSpace: namespace,
    data: {
      columns: [].concat(query.isRadio==7?columns1:columns, generateAction())
      ,//已发布的活动不能添加和删除时间段
      pageConfig:{},
      tableData: {total: '',dataSource: tableData},
      selectedRowKeys:'',
    },
    scroll: { x: '60%' },
    paginationFlag : false,
    loading
  }

  // 表格操作区域
  function generateAction () {
    return {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 120,
      render: (data, record, index) => {
        return (
          actionType == 'check'||query.systemType == '系统项'?null:
          <span>
              <a href='javascript:void(0)' onClick={() => {deleteItem(data,record, index)}}>
                删除
              </a>
          </span>
        )
      }
    }
  }
  // 添加
  function addTableRow(){
    tableObj.key = ++keys
    let obj = JSON.parse(JSON.stringify(tableObj))
    tableData.push(obj)

    dispatch({
      type: `${namespace}/updateStore`,
      payload: {tableData,keys}
    })
  }

  //删除选中项
  function deleteItem(data,record) {
    let arr = tableData&&tableData.length?tableData.filter(item => item.key != data.key):[]
    tableData = arr
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {tableData}
    })
  }

  function defaultValueChange(value,it){
    for(let item of tableData){
      item.defaultValue = 0
      if(item.key == it.key&&value){
        item.defaultValue = 1
      }
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {tableData}
    })
  }

  //输入框改变时
  function inputChange(e, name) {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {
        query: {
          ...query,
          [name]: e,
        }
      }
    })
  }
  function inputSystemChange(value,name,type){
    if(type == 'selete'){
      for(var item of systemData){
        if(item.attributeName == value){
          query.attributeName = item.attributeName
          query.isShow = item.isShow
          query.isRadio = item.isRadio
          query.itemContent = item.itemContent
          query.defaultValue = item.defaultValue
          if(!item.itemContent) return
          if(item.isRadio == 7){
            let arr2 = []
            let itemContentObj = JSON.parse(item.itemContent)
            for (let i in itemContentObj) {
                let o = {
                  key: i,
                  defaultValue: 0,
                  itemContent1: itemContentObj[i],
                  itemContent: i
                };
                if(i == item.defaultValue){
                  o.defaultValue = 1;
                }
                arr2.push(o)
            }
            tableData = arr2
          }else{
            let list =  item.itemContent.split(",")
            let arr = []
            for(var itt of list){
              let obj ={
                key:'a'+itt,
                defaultValue: 0,
                itemContent: itt,
              }
              if(itt == item.defaultValue){
                obj.defaultValue = 1
              }
              arr.push(obj)
            }
            tableData = arr
          }
        }
      }
      dispatch({
        type: `${namespace}/updateStore`,
        payload: {query,tableData}
      })
    }

    if(type == 'input'){
      let obj = {[name]: value}
      query = Object.assign(query, obj)
      dispatch({
        type: `${namespace}/updateStore`,
        payload: {query}
      })
    }
  }

  function inputAreaChange(value, name){
    for(var item of areaList){
      if(item.value == value){
        query.areaName = item.label
        query.areaId = value
      }
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {query}
    })
    dispatch({
      type: `${namespace}/filterProjectList`,
      payload: {areaId: value}
    })
    dispatch({
      type: `${namespace}/getPranentAtt`,
      payload: {areaId: value}
    })
  }
  function inputProjectChange(value, name){
    for(var item of products){
      if(item.value == value){
        query.projectName = item.label
        query.projectId = value
      }
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {query}
    })
  }
  
  //表格改变时
  function tableChange (value, name,id) {
    let obj = {[name]: value}
    for(var item of tableData){
      if(item.key == id){
        item = Object.assign(item, obj)
      }
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {query}
    })
  }
  function submit(){
    validateFieldsAndScroll((err) => {
      if (err) {
        return false
      } else {
        dispatch({
          type: `${namespace}/submit`,
          payload: {}
        })
      }
    })
  }
  return (
    <div className='public_listMain'>
      <div className={"functionButton"}>
        <Button disabled={actionType == 'check'} type='primary' onClick={e => submit()} loading={btnLoading}>提交</Button>
      </div>

      <CollapsiblePanels title="项目表单配置详情" hideUpDownBtn={true} >
        <Row>
          <Col span={8}>
            <FormItem label='区域'  {...formItemLayoutPro}>
              {getFieldDecorator('areaId', {
                rules: [{
                  required: true, whitespace: true, message: '请选择区域'
                }],
                initialValue: query.areaId
              })(
                <Select disabled={actionType == 'check'||query.systemType == '系统项'}  placeholder='请选择区域' onChange={(e) => { inputAreaChange(e, 'areaId') }}>
                  {areaList == undefined ?null:areaList.map((item)=>{
                      return <Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>
                    })}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='项目'  {...formItemLayoutPro}>
              {getFieldDecorator('projectId', {
                rules: [{
                  required: true, whitespace: true, message: '请选择项目'
                }],
                initialValue: query.projectId
              })(
                <Select disabled={actionType == 'check'||query.systemType == '系统项'}  placeholder='请选择项目' onChange={(e) => { inputProjectChange(e, 'projectId') }}>
                  {products == undefined ?null:products.map((item)=>{
                      return <Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>
                    })}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='表单名称'  {...formItemLayoutPro}>
              {getFieldDecorator('tableName', {
                rules: [{
                  required: true, whitespace: true, message: '请选择表单名称'
                }],
                initialValue: query.tableName
              })(
                <Select disabled={actionType == 'check'||query.systemType == '系统项'} placeholder='请选择表单名称' onChange={(e) => { inputChange(e, 'tableName') }}>
                      <Select.Option value="土拍市场">土拍市场</Select.Option>
                      <Select.Option value="政策盘点">政策盘点</Select.Option>
                      <Select.Option value="竞品管理">竞品管理</Select.Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='关键固定字段'  {...formItemLayoutPro}>
              {getFieldDecorator('systemType', {
                rules: [{
                  required: true, whitespace: true, message: '请选择关键固定字段'
                }],
                initialValue: query.systemType
              })(
                <Select disabled={actionType == 'check'||actionType == 'edit'} placeholder='请选择关键固定字段' onChange={(e) => { inputChange(e, 'systemType') }}>
                      <Select.Option value="自定义">自定义</Select.Option>
                      <Select.Option value="系统项">系统项</Select.Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='所属页签'  {...formItemLayoutPro}>
              {getFieldDecorator('tableTab', {
                rules: [{
                  required: true, whitespace: true, message: '请选择所属页签'
                }],
                initialValue: query.tableTab
              })(
                <Select disabled={actionType == 'check'} placeholder='请选择所属页签' onChange={(e) => { inputChange(e, 'tableTab') }}>
                      <Select.Option value="基本信息">基本信息</Select.Option>
                      <Select.Option style={{display: query.tableName == '竞品管理'?'block':'none'}} value="产品信息">产品信息</Select.Option>
                      <Select.Option style={{display: query.tableName == '土拍市场'?'block':'none'}} value="土地信息">土地信息</Select.Option>
                      <Select.Option style={{display: query.tableName == '政策盘点'?'block':'none'}} value="限购政策">限购政策</Select.Option>
                      <Select.Option style={{display: query.tableName == '政策盘点'?'block':'none'}} value="限售政策">限售政策</Select.Option>
                      <Select.Option style={{display: query.tableName == '政策盘点'?'block':'none'}} value="限价政策">限价政策</Select.Option>
                      <Select.Option style={{display: query.tableName == '政策盘点'?'block':'none'}} value="限签政策">限签政策</Select.Option>
                      <Select.Option style={{display: query.tableName == '政策盘点'?'block':'none'}} value="限贷政策">限贷政策</Select.Option>
                      <Select.Option style={{display: query.tableName == '政策盘点'?'block':'none'}} value="其他政策">其他政策</Select.Option>
                      <Select.Option style={{display: query.tableName == '政策盘点'?'block':'none'}} value="异动政策">异动政策</Select.Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        {query.systemType=='自定义'||query.systemType==''?<Row> 
          <Col span={8}>
            <FormItem label='字段名称'  {...formItemLayoutPro}>
              {getFieldDecorator('attributeName', {
                rules: [{
                  required: true, whitespace: true, message: '请输入字段名称'
                }],
                initialValue: query.attributeName
              })(
                <Input disabled={actionType == 'check'||query.systemType == '系统项'} placeholder='请输入字段名称'  onChange={(e) => { inputSystemChange(e.target.value, 'attributeName','input') }} />
              )}
            </FormItem>
          </Col>
        </Row>:null}
        {query.systemType=='系统项'?<Row>
          <Col span={8}>
            <FormItem label='字段名称'  {...formItemLayoutPro}>
              {getFieldDecorator('attributeName', {
                rules: [{
                  required: true, whitespace: true, message: '请输入字段名称'
                }],
                initialValue: query.attributeName
              })(
                <Select disabled={actionType == 'check'}  placeholder='请选择区域' onChange={(e) => { inputSystemChange(e, 'attributeName','selete') }}>
                  {systemNameList == undefined ?null:systemNameList.map((item)=>{
                      return <Select.Option key={item.label} value={item.label}>{item.label}</Select.Option>
                    })}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>:null}
        <Row>
          <Col span={8}>
            <FormItem label='必填设置'  {...formItemLayoutPro}>
              {getFieldDecorator('isShow', {
                rules: [{
                  required: true, whitespace: true, message: '请选择必填设置'
                }],
                initialValue: query.isShow
              })(
                <Select disabled={actionType == 'check'||query.systemType == '系统项'} placeholder='请选择必填设置' onChange={(e) => { inputChange(e, 'isShow') }}>
                  <Select.Option value="0">非必填</Select.Option>
                  <Select.Option value="1">必填</Select.Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='控件类型'  {...formItemLayoutPro}>
              {getFieldDecorator('isRadio', {
                rules: [{
                  required: true, whitespace: true, message: '请选择控件类型'
                }],
                initialValue: query.isRadio
              })(
                <Select disabled={actionType == 'check'||query.systemType == '系统项'} placeholder='请选择控件类型' onChange={(e) => { inputChange(e, 'isRadio') }}>
                      <Select.Option value="1">单选</Select.Option>
                      <Select.Option value="2">多选</Select.Option>
                      <Select.Option value="3">文本</Select.Option>
                      <Select.Option value="4">segment框</Select.Option>
                      <Select.Option value="5">日期</Select.Option>
                      <Select.Option value="6">富文本</Select.Option>
                      <Select.Option value="7">媒体类型</Select.Option>
                      <Select.Option value="8">固定值</Select.Option>
                      <Select.Option value="9">多选+输入框</Select.Option>
                      <Select.Option value="10">地址</Select.Option>
                      <Select.Option value="11">城市</Select.Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={8}>
            <FormItem label='排序'  {...formItemLayoutPro}>
              {getFieldDecorator('sort', {
                rules: [{
                  required: true, whitespace: true, message: '请输入排序'
                },{ pattern: /^[1-9]\d*$/, message: '请输入整数' }],
                initialValue: query.sort + ''
              })(
                <Input disabled={actionType == 'check'} placeholder='请输入排序'  onChange={(e) => { inputChange(e.target.value, 'sort') }} />
              )}
            </FormItem>
          </Col>
        </Row>
      </CollapsiblePanels>
      <div className="clearfix mgb1" style={{width: '95%',paddingLeft: '5%'}}>
        <div className={'fl'}>扩展配置项（单选或多选时配置）</div>
        <div style={{display: query.isRadio==1||query.isRadio == 2||query.isRadio == 8||query.isRadio == 7?'inline-block':'none'}}>
          <Button disabled={actionType == 'check'||query.systemType == '系统项'}  type='primary' onClick={() => { addTableRow() }}>添加</Button>
        </div>
      </div>
      <div className={'mt1', 'table_projectList'} style={{width: '95%',paddingLeft: '5%'}}>
        <Form style={{display: query.isRadio==1||query.isRadio == 2||query.isRadio == 8||query.isRadio == 7?'inline-block':'none'}}>
          <Grid {...gridProps}/>
        </Form>
      </div>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(projectListDetailView))